define(["knockout", 'jquery', "dynaWindow", "text!./roles.btl", 'jqx-all', 'ko-rest', 'ko-mapping'], 
		function (ko, $, dynaWindow, curBtl) {  		
    function ViewModel(params, componentInfo) {	
    	var self = this;
    	
    	self.element = $(componentInfo.element);
    	
    	self.email =  ko.observable('');
    	self.name =  ko.observable('');

    	self.queryWin = null;
    	self.solutionWin = null;
    	self.createWin = null;
    	
    	ko.postbox.subscribe(function(data) {
    	    	self.refresh();
    		}, 
    		null, "account-editor-pub");
    	
    	self.entities = ko.observableArray();
    	self.service = ko.rest.service('/rest/auth/role');
    	self.refresh();
	}  
    
    ViewModel.prototype.refresh = function() {
    	var self = this;
    	self.service.query(function(data) {
    		self.entities(data);
        });
    }
 
    ViewModel.prototype.update = function() {
    	var self = this;
    	var rowindex = self.element.find('#entities').jqxGrid('getselectedrowindex');
    	if (rowindex < 0) {
    		return;
    	}
    	
    	ko.postbox.notifySubscribers(
    		{isEditor: true, id: self.entities()[rowindex].id}, "account-editor-sub");
    	
    	this.createWin.show();
    }
    
    ViewModel.prototype.delete = function() {
    	var self = this;
    	var rowindex = self.element.find('#entities').jqxGrid('getselectedrowindex');
    	if (rowindex < 0) {
    		return;
    	}
    	self.service.delete(self.entities()[rowindex].id, function() {
    		self.refresh();
        });
    }
    
    ViewModel.prototype.onToolbarClick = function(event) {
    	var self = this;
    	var item = $(event.args).find(".toolbar-item")[0];
    	if (item.id == "solution") {
    		this.solutionWin.show();
    	} else if (item.id == "query") {
    		this.queryWin.show();
    	} else if (item.id == "create") {
        	ko.postbox.notifySubscribers({isEditor: false, id: -1},  "account-editor-sub");
    		this.createWin.show();
    	} else if (item.id == "delete") {
    		self.delete();
    	} else if (item.id == "refresh") {
    		self.refresh();
    	} else if (item.id == "update") {
    		self.update();
    	}
    };
    
    return {  viewModel: {
        createViewModel: function (params, componentInfo) {
            var vm = new ViewModel({}, componentInfo);
            $(componentInfo.element).find("#menu").on('itemclick', function (event){
            	vm.onToolbarClick(event);
            });

			vm.solutionWin = new dynaWindow(componentInfo.element, 'qs-win');
			vm.queryWin = new dynaWindow(componentInfo.element, 'ref-win');
			vm.createWin = new dynaWindow(componentInfo.element, 'account-editor');
            return vm;
        }
    }, template:curBtl };
    
});
